package com.lenovo.newsapp.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.zip.GZIPInputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class HttpUtil {

	private static final int CONNECTION_TIMEOUT = 30000;
	private static final int SO_TIMEOUT = 30000;
	public static String PARSER_UNICODE = "GBK";

	public static final String GBK = "GBK";
	public static final String UTF_8 = "utf-8";

	public static final int DO_POST = 0;
	public static final int DO_GET = 1;

	/**
	 * post
	 * 
	 * @param url
	 * @param nameValuePairs
	 * @throws Exception
	 */
	public static HttpResponse doPost(String url,
			List<NameValuePair> nameValuePairs) throws Exception {
		HttpParams httpParams = new BasicHttpParams();
		setHttpParams(httpParams);

		DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
		HttpPost httpPost = new HttpPost(url);
		httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs,
				PARSER_UNICODE));
		HttpResponse httpResponse = httpClient.execute(httpPost);
		int res = httpResponse.getStatusLine().getStatusCode();
		if (200 != res)
			throw new Exception();

		return httpResponse;
	}

	/**
	 * get
	 * 
	 * @param url
	 * @throws Exception
	 */
	public static HttpResponse doGet(String url) throws Exception {
		HttpParams httpParams = new BasicHttpParams();
		setHttpParams(httpParams);

		DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
		HttpGet httpGet = new HttpGet(url);
		HttpResponse httpResponse = httpClient.execute(httpGet);
		int res = httpResponse.getStatusLine().getStatusCode();
		if (200 != res)
			throw new Exception();

		return httpResponse;
	}

	private static void setHttpParams(HttpParams httpParams) {
		HttpConnectionParams.setConnectionTimeout(httpParams,
				CONNECTION_TIMEOUT);
		HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
	}

	/**
	 * 判断是否有网络连接
	 * 
	 * @param activity
	 * @return
	 */
	public static boolean isNetworkAvailable(Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		if (connectivity == null) {
			return false;
		} else {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i ++ ) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}

	/**
	 * 通过post方式获取jsonObject
	 * 
	 * @param url
	 * @param nameValuePairs
	 * @param isGzip
	 * @return
	 * @throws Exception
	 */
	public static JSONObject getJSONObjFromUrlByPost(String url,
			List<NameValuePair> nameValuePairs, boolean isGzip)
			throws Exception {
		return getJSONObjFromUrl(DO_POST, url, nameValuePairs, isGzip);
	}

	/**
	 * 通过get方式从url获取jsonObject
	 * 
	 * @param url
	 * @param isGzip
	 * @return
	 * @throws Exception
	 */
	public static JSONObject getJSONObjFromUrlByGet(String url, boolean isGzip)
			throws Exception {
		return getJSONObjFromUrl(DO_GET, url, null, isGzip);
	}

	/**
	 * 通过get方式获取JSONArray
	 * 
	 * @param url
	 * @param isGzip
	 * @return
	 * @throws Exception
	 */
	public static JSONArray getJSONArrayFromUrlByGet(String url, boolean isGzip)
			throws Exception {
		return getJSONArrayFromUrl(DO_GET, url, null, isGzip);
	}

	/**
	 * 通过post方式获取JSONArray
	 * 
	 * @param url
	 * @param nameValuePairs
	 * @param isGzip
	 * @return
	 * @throws Exception
	 */
	public static JSONArray getJSONArrayFromUrlByPost(String url,
			List<NameValuePair> nameValuePairs, boolean isGzip)
			throws Exception {
		return getJSONArrayFromUrl(DO_POST, url, nameValuePairs, isGzip);
	}

	/**
	 * 从url获取JSONObject
	 * 
	 * @param type
	 * @param url
	 * @param nameValuePairs
	 * @param isGzip
	 * @return
	 * @throws Exception
	 */
	public static JSONObject getJSONObjFromUrl(int type, String url,
			List<NameValuePair> nameValuePairs, boolean isGzip)
			throws Exception {
		String jsonStr = getReturnStrFromUrl(type, url, nameValuePairs, isGzip);
		return new JSONObject(jsonStr);
	}

	/**
	 * 获取JSONArray
	 * 
	 * @param type
	 * @param url
	 * @param nameValuePairs
	 * @param isGzip
	 * @return
	 * @throws Exception
	 */
	public static JSONArray getJSONArrayFromUrl(int type, String url,
			List<NameValuePair> nameValuePairs, boolean isGzip)
			throws Exception {
		String jsonStr = getReturnStrFromUrl(type, url, nameValuePairs, isGzip);
		return new JSONArray(jsonStr);
	}

	public static String getReturnStrFromUrl(int type, String url,
			List<NameValuePair> nameValuePairs, boolean isGzip)
			throws Exception {
		HttpResponse httpResponse;
		if (type == DO_POST) {
			httpResponse = HttpUtil.doPost(url, nameValuePairs);
		} else {
			httpResponse = HttpUtil.doGet(url);
		}

		HttpEntity httpEntity = httpResponse.getEntity();
		InputStream is = httpEntity.getContent();
		if (isGzip) {
			is = new GZIPInputStream(is);
		}

		BufferedReader reader = new BufferedReader(new InputStreamReader(is,
				UTF_8), 8);
		StringBuilder sb = new StringBuilder();
		String line = null;
		while ((line = reader.readLine()) != null) {
			sb.append(line + "\n");
		}
		is.close();
		return sb.toString();
	}

}
